# -*- coding: utf-8 -*-

'''Definition of Image block objects. 

**The raw image block will be merged into TextBlock > Line > Span.**
'''
'''图像块对象的定义。

**原始图像块将被合并到 TextBlock > Line > Span 结构中。**
'''

from io import BytesIO
from ..text.Line import Line
from ..text.TextBlock import TextBlock
from .Image import Image
from .ImageSpan import ImageSpan
from ..common.Block import Block
from ..common.docx import add_float_image


class ImageBlock(Image, Block):
    '''Image block.'''
    '''图像块。'''
    def __init__(self, raw:dict=None):
        super().__init__(raw)

        # inline image type by default
        # 默认为内联图像类型
        self.set_inline_image_block()


    def to_text_block(self):
        """Convert image block to a span under text block.

        Returns:
            TextBlock: New TextBlock instance containing this image.
        """
        """将图像块转换为文本块下的span。

        返回:
            TextBlock: 包含此图像的新TextBlock实例。
        """
        # image span
        # 图像span
        span = ImageSpan().from_image(self)

        # add span to line
        # 将span添加到行
        image_line = Line()
        image_line.add(span)
        
        # insert line to block
        # 将行插入到块
        block = TextBlock()        
        block.add(image_line)

        # NOTE: it's an image block even though in TextBlock type
        # 注意：即使是TextBlock类型，它仍然是一个图像块
        block.set_inline_image_block() 

        return block
 

    def store(self):
        '''Store ImageBlock instance in raw dict.'''
        '''将ImageBlock实例存储在原始字典中。'''
        res = Block.store(self)
        res.update(
            Image.store(self)
        )
        return res

    
    def plot(self, page):
        '''Plot image bbox with diagonal lines (for debug purpose).
        
        Args: 
            page (fitz.Page): pdf page to plot.
        '''
        '''用对角线绘制图像边界框（用于调试目的）。
        
        参数: 
            page (fitz.Page): 要绘制的pdf页面。
        '''
        super().plot(page, color=(1,0,0))


    def make_docx(self, p):
        '''Create floating image behind text. 
        
        Args:
            p (Paragraph): ``python-docx`` paragraph instance.
        
        .. note::
            Inline image is created within TextBlock.
        '''
        '''在文本后面创建浮动图像。
        
        参数:
            p (Paragraph): ``python-docx``段落实例。
        
        .. 注意::
            内联图像是在TextBlock内创建的。
        '''
        if self.is_float_image_block:
            x0, y0, x1, y1 = self.bbox
            add_float_image(p, BytesIO(self.image), width=x1-x0, pos_x=x0, pos_y=y0)
        else:
            super().make_docx(p)
        return p